package decoder

import (
	"encoding/binary"
	"encoding/hex"
	"math"
)

type ByteReader struct {
	code []byte
	pc   int
}

func (this *ByteReader) reset(code []byte, pc int) {
	this.code = code
	this.pc = pc
}

func (this *ByteReader) Pc() int {
	return this.pc
}

func (this *ByteReader) finished() bool {
	return this.pc == len(this.code)
}

func (this *ByteReader) skip(byteIndex int) {
	this.pc += byteIndex
}

func (this *ByteReader) readUint8() uint8 {
	i := this.code[this.pc]
	this.pc++
	return i
}

func (this *ByteReader) readUint16() uint16 {
	byte1 := uint16(this.readUint8())
	byte2 := uint16(this.readUint8())
	return byte1 | (byte2 << 8)
}

func (this *ByteReader) readUint32() uint32 {
	byte1 := uint32(this.readUint8())
	byte2 := uint32(this.readUint8())
	byte3 := uint32(this.readUint8())
	byte4 := uint32(this.readUint8())
	return byte1 | (byte2 << 8) | (byte3 <<16) | (byte4 << 24)
}

func (this *ByteReader) readByte() byte {
	b := this.readUint8()
	return b
}
func (this *ByteReader) readBytes(byteIndex int) []byte {
	bytes := this.code[this.pc:this.pc+byteIndex]
	this.pc += byteIndex
	return bytes
}

func (this *ByteReader) readHexString(byteIndex int) string {
	bytes := this.readBytes(byteIndex)
	s := hex.EncodeToString(bytes)
	return s
}

func (this *ByteReader) readString() string {
	s := string(this.readUint8())
	return s
}

func (this *ByteReader) readMultiString(byteIndex int) string {
	bytes := this.readBytes(byteIndex)
	s := string(bytes)
	return s
}
func (this *ByteReader) readMultiDouble(byteIndex int) float64 {
	bytes := this.readBytes(byteIndex)
	bits := binary.LittleEndian.Uint64(bytes)
	float := math.Float64frombits(bits)
	return float
}
func (this *ByteReader) readMultiFloat(byteIndex int) float32 {
	bytes := this.readBytes(byteIndex)
	bits := binary.LittleEndian.Uint32(bytes)
	float := math.Float32frombits(bits)
	return float
}